package com.svtar.ywg.api;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.orhanobut.logger.Logger;
import com.svtar.ywg.utils.MD5;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 数据接口请求
 */
public class Api {

    private Api() {

    }

    private static Api sInstance;

    public static Api getInstance() {
        if (sInstance == null) {
            sInstance = new Api();
        }
        return sInstance;
    }

    /**
     * 得到一个可排序的map
     * ASCII码从小到大排序
     *
     * @return
     */
    public static Map<String, String> getSortMap() {
        Map<String, String> map = new TreeMap<>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        //升序排序
                        return obj1.compareTo(obj2);
                    }
                });
        return map;
    }

    /**
     * 对请求数据进行加密处理
     *
     * @param map
     * @return
     */
    public static String sign(Map<String, String> map, String signKey) {
        Map<String, String> signMap = getSortMap();
        signMap.putAll(map);
        //拼上密钥
        signMap.put("key", signKey);
        //返回MD5加密后的签名
        return MD5.md5(JSON.toJSONString(signMap));
    }

    /**
     * 签名验证
     */
    public void checkoutAttestation(SimpleCallback callback, String systemApi, String systemId, String signKey) {
        Map<String, String> map = getSortMap();
        map.put("test", "test");
        map.put("systemId", systemId);
        map.put("sign", sign(map, signKey));
        Logger.e("请求参数：" + JSON.toJSONString(map));
        String url = systemApi + ApiService.CHECKOUT_ATTESTATION;
        OkGo.<String>post(url)
                .tag(this)
                .params(map).execute(callback);
    }
}